package cn.founder.user.controller;

import cn.founder.basic.exception.BusinessException;
import cn.founder.basic.util.AjaxResult;
import cn.founder.basic.util.PageList;
import cn.founder.user.domain.User;
import cn.founder.user.dto.UserDto;
import cn.founder.user.query.UserQuery;
import cn.founder.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 前端用户模块
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/phone/register")
    public AjaxResult phoneRegister(@RequestBody UserDto userDto){
        try {
            //自定义 一个方法  内部含有其他的业务 比如验证客户信息是否重复等.
            userService.phoneRegister(userDto);
            return AjaxResult.myself();
        } catch (BusinessException e) {
            //使用自定义类   获取后端传来的具体错误信息
            e.printStackTrace();
            return AjaxResult.fail(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("注册失败");
        }
    }

    //查询一条数据
    @GetMapping("/{id}")
    public User queryOne(@PathVariable("id") Long id){
        return userService.queeryById(id);
    }

    //查询所有
    @GetMapping
    public List<User> queryAll(){
        return userService.queryAll();
    }

    //删除一条数据
    @DeleteMapping("/{id}")
    public AjaxResult delOne(@PathVariable("id") Long id){
        try {
            userService.del(id);
            return AjaxResult.myself();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("删除失败");
        }
    }

    //添加或修改
    @PutMapping
    public AjaxResult addorUpdata(@RequestBody User user){
        try {
            if (user.getId()==null){
                userService.add(user);
            }else {
                userService.update(user);
            }
            return  AjaxResult.myself();
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.fail("操作失败");
        }
    }

    //分页查询
    @PostMapping
    public PageList<User> queryPage(@RequestBody UserQuery query){
        return userService.queryPage(query);
    }



    //批量删除一条数据
    @PatchMapping
    public AjaxResult pathchDelete(@RequestBody List<Long> ids){
        try {
            userService.pathchDel(ids);
            return AjaxResult.myself();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("删除失败");
        }
    }

}
